package models

import (
	"encoding/json"
	"go-project/common"
)

const (
	SYSTEM_APP_GROUP             = "app"
	SYSTEM_OFFICIAL_ACCOUNT_NAME = "official_account"
	SYSTEM_RECORD_NAME           = "system_record"
	SYSTEM_SYSTEM_INFO_NAME      = "system_info"
)

type SystemOptions struct {
	ID        uint              `gorm:"primary_key" json:"id"`
	Name      string            `gorm:"type:varchar(255);not null;comment:'名称'" json:"name"`
	Group     string            `json:"group"`
	Value     string            `json:"value"`
	CreatedAt *common.LocalTime `json:"created_at"`
	UpdatedAt *common.LocalTime `json:"updated_at"`
}

func (s *SystemOptions) TableName() string {
	return "system_options"
}
func (s *SystemOptions) Get(value interface{}, key string, group string) error {
	if group == "" {
		group = SYSTEM_APP_GROUP
	}
	if key == "" {
		key = SYSTEM_SYSTEM_INFO_NAME
	}
	result := common.DB.Where("`name`=? and `group`=?", key, group).First(s)
	if result.RecordNotFound() {
		return nil
	} else if err := result.Error; err != nil {
		return err
	}
	err := json.Unmarshal([]byte(s.Value), value)
	if err != nil {
		return err
	}
	return nil
}
func (s *SystemOptions) Set(value any, key string, group string) error {
	if group == "" {
		group = SYSTEM_APP_GROUP
	}
	if key == "" {
		key = SYSTEM_SYSTEM_INFO_NAME
	}
	result := common.DB.Where("`name`=? and `group`=?", key, group).First(s)
	marshal, err := json.Marshal(value)
	if err != nil {
		return err
	}
	s.Name = key
	s.Group = group
	s.Value = string(marshal)
	if result.RecordNotFound() {
		result = common.DB.Create(s)
		if err := result.Error; err != nil {
			return err
		}
		return nil
	} else if err := result.Error; err != nil {
		return err
	} else {
		result = common.DB.Save(s)
		if err := result.Error; err != nil {
			return err
		}
		return nil
	}

}
